/*
 *     This file is part of Neptune Network Emulator.
 *
 *  Neptune Network Emulator is free software: 
 *  you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Neptune Network Emulator is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Neptune Network Emulator.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
/**
 *
 */
package neptune.web.client.view;


import neptune.web.client.WebInterface;
import neptune.web.client.services.ClusterService;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Luigi Lorenzo Arpino [luigiarpino@yahoo.it]
 *
 */
public class TaskView extends View implements ClickListener
{
	public static final String DEFAULT_TOKEN = "Task";
	private FlexTable taskTable;
	// Timeout in secondi
	static final int TIMEOUT = 4;
	private Timer elapsedTimer;

	public static final String QUEUED_IMG = "img/queued_32.png";
	public static final String RUNNING_IMG = "img/running_32.png";
	public static final String FINISHED_IMG = "img/finished_32.png";
	public static final String FAILED_IMG = "img/failed_32.png";
	public static final String TRASH_FULL_IMG = "img/trash_full_64x64.png";
	public static final String TRASH_EMPTY_IMG = "img/trash_empty_64x64.png";
	
	private PushButton butTrash;
	
	public TaskView()
	{
		// Setting view params
		try 
		{
			this.setName(TaskView.DEFAULT_TOKEN);
		}
		catch (DuplicatedTokenException e) 
		{
			ConsoleManager.addConsoleDebugMessage(e.getMessage(), true);
		}

		// Costruzione struttura interfaccia
		VerticalPanel vPanel = new VerticalPanel();
		vPanel.setSize("90%", "100%");

		// Header tabella Task
		FlexTable taskTableHeader = new FlexTable();
		taskTableHeader.setWidth("98%");
		taskTableHeader.setText(0, 0, "Description");
		taskTableHeader.setText(0, 1, " ");
		taskTableHeader.setText(0, 2, "State");
		taskTableHeader.setText(0, 3, "Elapsed Time");
		
		
		
		
		//pmTableHeader.getColumnFormatter().setWidth(0, "16px");
		//pmTableHeader.getColumnFormatter().setWidth(0, "11%");
		taskTableHeader.getColumnFormatter().setWidth(0, "60%");
		taskTableHeader.getColumnFormatter().setWidth(1, "3%");
		taskTableHeader.getColumnFormatter().setWidth(2, "22%");
		taskTableHeader.getColumnFormatter().setWidth(3, "15%");
		
		vPanel.add(taskTableHeader);

		taskTable = new FlexTable();
		taskTable.setWidth("98%");
		ScrollPanel pmTableWrap = new ScrollPanel(taskTable);
		pmTableWrap.setSize("100%", "400px");
		vPanel.add(pmTableWrap);

		
		HorizontalPanel menuPanel=new HorizontalPanel();
		
		butTrash=new PushButton(new Image(TRASH_FULL_IMG), new Image(TRASH_EMPTY_IMG));
		butTrash.addClickListener(this);
		butTrash.setTitle("Delete finished jobs");
		butTrash.setEnabled(false);
		butTrash.setVisible(false);
		menuPanel.add(butTrash);
		
		
		

         
        
		VerticalPanel mainPanel=new VerticalPanel();
		mainPanel.add(menuPanel);
		mainPanel.add(vPanel);
		
		initWidget(mainPanel);

		// Styles
		vPanel.setStylePrimaryName("ClusterView");
		taskTableHeader.setStylePrimaryName("ClusterView-pmTable");
		taskTableHeader.addStyleDependentName("header");
		pmTableWrap.setStylePrimaryName("ClusterView-pmTableWrap");
		taskTable.setStylePrimaryName("ClusterView-pmTable");
		
		elapsedTimer = new Timer () 
		{
		      public void run() 
		      {
		    	  readDataFromServer();
		      }
		};
	
	}
	
	private void readDataFromServer()
	{
		ClusterService.Util.getInstance().getTask(new AsyncCallback<String[][]>()
		{

			public void onFailure(Throwable caught) 
			{
				String message=new String("Error Unable to read task: "+caught.getMessage() );
            	WebInterface.addMessageToConsoleAndShowDialog(message,true);
			}

			public void onSuccess(String[][] result) 
			{
				handlerData(result);
			}

		});
		
	}
	
	private void handlerData(String[][] result) 
	{
		int row = taskTable.getRowCount();
		for (int i=0 ; i<row ;i++)
		{
			taskTable.removeRow(0);
		}
		// inserisco le nuove righe
		for (int i=0 ; i<result.length ;i++)
		{
			taskTable.setWidget(i, 0, new TaskPanel(result[i][0],result[i][1], result[i][2]) );
		}
		// verifico se non ci sono task da mostrare
		if (result.length==0)
		{
			taskTable.setWidget(0, 0, new TaskPanel("No items to display","--", "--") );
		}
		//verifico se ci sono task finiti
		boolean isTrashFull=false;
		for (int i=0 ; i<result.length ;i++)
		{
			if (result[i][1].equalsIgnoreCase("Finish"))
				isTrashFull=true;
		}
		if (isTrashFull)
		{
			this.butTrash.setEnabled(true);
			this.butTrash.setVisible(true);
		}
		else
		{
			this.butTrash.setEnabled(false);
			this.butTrash.setVisible(false);
		}
		
		
		// verifico se occorre aggiornare i dati
		SuperView view =  (SuperView)ViewManager.getViewManager().getActiveView();
		String nameView = view.getActiveView().getName();
		if ( nameView.equalsIgnoreCase( TaskView.DEFAULT_TOKEN ) )
		{
			this.elapsedTimer.schedule(TIMEOUT *1000);
		}
		else
		{
			//System.out.println("fermo il timer");
		}
	}
	
	public void startPollingToServer()
	{
		//System.out.println("Faccio partire il timer");
		readDataFromServer();
	}
	
	public class TaskPanel extends Composite
	{
	
		public TaskPanel(String name, String state, String elapsedTime)
		{
			
			
			VerticalPanel vPanel = new VerticalPanel();
			vPanel.setSize("100%", "100%");
	
			FlexTable dataTable = new FlexTable();
			dataTable.setWidth("100%");
			//img.setTitle(descrizione);
			dataTable.setText(0, 0, name);
			if (state.equalsIgnoreCase("Failed"))
			{
				dataTable.setWidget( 0, 1, new Image(FAILED_IMG) );
				dataTable.setText(0, 2, " Failed ");
			}
			else if ( state.equalsIgnoreCase("Finish") )
			{
				dataTable.setWidget( 0, 1, new Image(FINISHED_IMG) );
				dataTable.setText(0, 2, " Finish ");
			}
			else if ( state.equalsIgnoreCase("Queued") )
			{
				dataTable.setWidget( 0, 1, new Image(QUEUED_IMG) );
				dataTable.setText(0, 2, " Queued ");	
			}
			else if ( state.equalsIgnoreCase("Running") )
			{
				dataTable.setWidget( 0, 1, new Image(RUNNING_IMG) );
				dataTable.setText(0, 2, " Running ");
			}		
			else
			{
				dataTable.setWidget( 0, 1, null );
				dataTable.setText(0, 2, " Not Defined ");
			}
			dataTable.setText(0, 3, elapsedTime);
			//dataTable.getColumnFormatter().setWidth(0, "200px");
			dataTable.getColumnFormatter().setWidth(0, "60%");
			dataTable.getColumnFormatter().setWidth(1, "5%");
			dataTable.getColumnFormatter().setWidth(2, "25%");
			dataTable.getColumnFormatter().setWidth(3, "10%");
			
			vPanel.add(dataTable);
	
			initWidget(vPanel);
			// Styles
			vPanel.setStylePrimaryName("ClusterView-NodePanel");
			dataTable.setStylePrimaryName("ClusterView-NodePanel-dataTable");
		}
	}

	/* (non-Javadoc)
	 * @see com.google.gwt.user.client.ui.ClickListener#onClick(com.google.gwt.user.client.ui.Widget)
	 */
	public void onClick(Widget sender)
	{
		this.butTrash.setEnabled(false);
		this.butTrash.setVisible(false);
		// rimuovo tutte le righe
		int row = taskTable.getRowCount();
		for (int i=0 ; i<row ;i++)
		{
			taskTable.removeRow(0);
		}
		ClusterService.Util.getInstance().removeAllFinishedJobs(new AsyncCallback<Boolean>()
		{
			public void onFailure(Throwable caught){}

			public void onSuccess(Boolean result){}
		});	
	}
	

}
